package com.pss.order.exception;

import com.pss.common.exception.BaseException;
import com.pss.common.exception.ErrorCodes;
import com.pss.common.response.Response;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public Response customExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) {
        e.printStackTrace();
        return Response.error(ErrorCodes.SYSTEM_ERROR.getValue(), ErrorCodes.SYSTEM_ERROR.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public Response baseExceptionHandler(HttpServletRequest request, final BaseException e, HttpServletResponse response) {
        return Response.error(e.getCode(), e.getMessage());
    }
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Response httpMessageNotReadableExceptionHandler(HttpServletRequest request, final HttpMessageNotReadableException e, HttpServletResponse response) {
        return Response.error(ErrorCodes.SYSTEM_ERROR.getValue(), "数据格式不正确");
    }
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Response dataIntegrityViolationExceptionHandler(HttpServletRequest request, final DataIntegrityViolationException e, HttpServletResponse response) {
        e.printStackTrace();
        return Response.error(ErrorCodes.SYSTEM_ERROR.getValue(), "存在关联数据，无法操作");
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Response methodArgumentNotValidExceptionHandler(HttpServletRequest request, final MethodArgumentNotValidException e, HttpServletResponse response) {
        BindingResult bindingResult = e.getBindingResult();
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        List<String> errorMessages = new ArrayList<>();
        for(ObjectError error :allErrors) {
            errorMessages.add(error.getDefaultMessage());
        }
        return Response.error(ErrorCodes.SYSTEM_ERROR.getValue(), String.join("，", errorMessages));
    }

}
